<template>
  <div class="app-container calendar-list-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input clearable class="filter-item" style="width: 200px;" placeholder="请输入商品名称" v-model="listQuery.name">
      </el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button class="filter-item" type="primary" @click="handleCreate" icon="el-icon-edit">添加</el-button>
      <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table size="small" :data="list" v-loading="listLoading" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="商品编号：">
              <span>{{ props.row.productCode }}</span>
            </el-form-item>
            <el-form-item label="商品名称:">
              <span>{{ props.row.name }}</span>
            </el-form-item>
             <el-form-item label="商品副标题:">
              <span>{{ props.row.subtitle }}</span>
            </el-form-item>
            <el-form-item label="所属分类:">
              <span>{{ props.row.categoryName }}</span>
            </el-form-item> 
            <el-form-item label="商品规格">
              <el-popover placement="right" width="350" trigger="click">
                 <el-table :data="props.row.productSpecs">
                 <el-table-column width="120" property="name" label="名称"></el-table-column>
                 <el-table-column width="100" property="price" label="价格"></el-table-column>
                 <el-table-column width="100" property="stock" label="库存"></el-table-column>
                </el-table>
              <el-button size="mini" slot="reference" >点击查看</el-button>
              </el-popover>
            </el-form-item>     
                     
            <el-form-item label="排序:">
              <span>{{ props.row.sortOrder }}</span>
            </el-form-item>
            <el-form-item label="创建时间:">
              <span>{{ props.row.createTime }}</span>
            </el-form-item>
            <el-form-item label="修改时间:">
              <span>{{ props.row.updateTime }}</span>
            </el-form-item>
            <el-form-item label="状态:">
              <span>{{ props.row.status| formatStata}}</span>
            </el-form-item>
            <el-form-item label="备注:">
              <span>{{ props.row.comment }}</span>
            </el-form-item>
          </el-form>          
        </template>
      </el-table-column>

      <el-table-column align="center" type="selection" width="55" prop="id"/>
      
       <el-table-column align="center" min-width="100px" label="商品编号" prop="productCode" sortable/>

      <el-table-column align="center" min-width="100px" label="商品名称" prop="name" sortable/>

      <el-table-column align="center" min-width="100px" label="商品所属分类" prop="categoryName" sortable/>

    

     <el-table-column align="center" min-width="100px" label="排序" prop="sortOrder" sortable/>

     <el-table-column align="center" min-width="100px" label="状态" prop="status"
        :filters="[{ text: '删除', value: 0 }, { text: '在售', value: 1 }, { text: '下架', value: 2 }]" :filter-method="filterStatus">
      <template slot-scope="scope">
         <el-tag :type="scope.row.status | statusFilter">{{scope.row.status| formatStata}}</el-tag>
      </template>
     </el-table-column>     

      <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini"  @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
        :page-sizes="[10,20,30,50]" :page-size="listQuery.sie" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibilityHeight="100" ></back-to-top>
    </el-tooltip>

    <!-- 添加或修改对话框 -->
    <el-dialog  width="60%" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :before-close="cancel">
      <el-form  :rules="rules"  ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px" >

         <el-form-item  label="商品编号" prop="productCode" v-if="this.dialogStatus === 'update'">
          <el-input v-model="dataForm.productCode"/>
        </el-form-item>  

        <el-form-item  label="商品名称" prop="name">
          <el-input v-model="dataForm.name"/>
        </el-form-item>  
        <el-form-item  label="商品副标题" prop="subtitle">
          <el-input  v-model="dataForm.subtitle"/>
        </el-form-item> 

        
         <el-form-item  label="所属分类">
           <el-cascader v-model="categoryIds"  placeholder="请选择商品分类"  :options="listCName" :show-all-levels="true" filterable></el-cascader>
         </el-form-item> 

        <el-form-item label="商品图片">
          <el-upload :action='UPLOAD_API' :limit='5' multiple accept=".jpg,.jpeg,.png,.gif"  :before-upload="beforeAvatarUpload"  list-type="picture-card" :on-exceed='uploadOverrun' :on-success="handleGalleryUrl" :on-remove="handleRemove">
           <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>        

         <el-form-item  label="商品详细" prop="detail"> 
          <el-upload class="upload-demo" action="" accept=".jpg,.jpeg,.png,.gif"   list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
         </el-form-item>  
       
        <el-form-item  label="排序" prop="sortOrder">
          <el-input  v-model="dataForm.sortOrder" placeholder="数字越小越靠前"/>
        </el-form-item>
      
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="handleSpecs">下一步</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

     <!-- 添加或修改规格对话框 -->
    <el-dialog  width="60%" :title="textMap[dialogStatus]" :visible.sync="dialogFormSpecs" :before-close="cancel">
      <el-form  :rules="rules"  ref="dataForm" :model="dataForm" status-icon label-position="left" label-width="100px"  >
      
        <el-form-item :inline="true" v-for="(item,index) in skuList" :label="'规格'+(index+1)" prop="sortOrder" :key="index" >
          <el-upload :action='UPLOAD_API' :limit='1' accept=".jpg,.jpeg,.png,.gif"  :before-upload="beforeAvatarUpload"  list-type="picture-card" :on-exceed='skuUploadOverrun' :on-success="handleGalleryUrl" :on-remove="handleRemove" >
           <i class="el-icon-plus"></i>
          </el-upload>
          <el-input v-model="item.name" placeholder="规格名称" style="width:25%"/>
          <el-input v-model.number="item.price" placeholder="价格" style="width:25%"/>
          <el-input v-model.number="item.stock" placeholder="库存" style="width:25%"/>
        </el-form-item>
        
        <el-form-item>
          <el-button @click="addSku">添加规格</el-button>
          <el-button @click="delSku" type="danger">删除规格</el-button>
        </el-form-item>

      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="dialogFormSpecs = false,dialogFormVisible = true">上一步</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData" >提交</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<style>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>

<script>
import { listGoods, createGoods, updateGoods, deleteGoods } from "@/api/goods";
import { listCategoryName } from "@/api/category";
import { createStorage } from "@/api/storage";
import waves from "@/directive/waves"; // 水波纹指令
import BackToTop from "@/components/BackToTop";
import Editor from "@tinymce/tinymce-vue";

export default {
  name: "Goods",
  components: { BackToTop, Editor },
  directives: { waves },
  data() {
    return {
      // 商品规格列表，默认为空
      skuList: [],

      list: undefined,

      //商品总数
      total: undefined,

      listLoading: true,

      //分页属性
      listQuery: {
        page: 1,
        size: 10,
        name: undefined,
        sort: "id"
      },

      //商品属性
      dataForm: {
        id: undefined,

        categoryId:undefined,

        productCode: '',

        name: undefined,

        subtitle: undefined,

        subImage: undefined,
        detail: undefined,
        sortOrder: undefined,
        status: "",
        productSpecs: undefined,
        comment: "",
      },

      //单个商品类目级联
      categoryIds:[],

      //类目列表
      listCName: [],

      //商品基本信息dialog
      dialogFormVisible: false,

      //商品规格信息
      dialogFormSpecs: false,

      //dialo对话框的状态
      dialogStatus: "",

      textMap: {
        update: "编辑",
        create: "创建",
        image: "商品图片",
        specs: "规格"
      },
      rules: {
        productCode: [{ required: true, message: "商品编号不能为空", trigger: "blur"}],
        name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
        subtitle:[{required:true,message:"副标题不能为空",trigger:"blur"}],
        categoryName:[{required:true,message:"所属分类不能为空",trigger:"blur"}]
        
      },

      downloadLoading: false,

    };
  },
  created() {
    this.getList()
    //加载商品级联分类
    this.getListCategoryName()
  },
  filters: {
    //状态的对应的type样式
    statusFilter(status) {
      const statusMap = {
        0: "danger",
        1: "success",
        2: "info"
      };
      return statusMap[status];
    },
    // 状态显示转换
    formatStata(status) {
      const statusMap = {
        0: "删除",
        1: "在售",
        2: "下架"
      };
      return statusMap[status];
    }
  },
  methods: {
    //获取商品集合
    getList () {
      this.listLoading = true;
      listGoods(this.listQuery)
        .then(response => {
          this.list = response.data.data.products;
          this.total = response.data.data.page.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        categoryName: undefined,
        name: undefined,
        productCode: '',
        subtitle: undefined,
        subImage: undefined,
        detail: true,
        sortOrder: undefined,
        status: "",
        productSpecs: undefined,
        comment: ""
      };
    },

    
    filterStatus(value, row) {
      return row.status === value;
    },

    uploadOverrun: function() {
      this.$message({
        type: "error",
        message: "上传文件个数超出限制!最多上传5张图片!"
      });
    },

    skuUploadOverrun () {
      this.$message({
        type: "error",
        message: "上传文件个数超出限制!最多上传1张图片!"
      })
    },
    
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.dataForm.gallery.push(response.data.url);
      }
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.dataForm.gallery.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url;
        if (file.response === undefined) {
          url = file.url;
        } else {
          url = file.response.data.url;
        }

        if (this.dataForm.gallery[i] === url) {
          this.dataForm.gallery.splice(i, 1);
        }
      }
    },
    //添加商品（基本信息）
    handleCreate() {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate()
      })
   
    },

    //初始化分类列表
    getListCategoryName(){
    
      if(this.listCName.length === 0){
        listCategoryName().then(res => {
          const resData = res.data.data
          for (let r in resData) {
              let data = {
                value: resData[r].id,
                label: resData[r].name,
                children: []
              }
              let childrenArrary = []
              for (let i in resData[r].childCategroys) {
                let children = {
                  value: resData[r].childCategroys[i].id,
                  label: resData[r].childCategroys[i].name
                }
                childrenArrary.push(children)
              }
              data.children = childrenArrary
              this.listCName.push(data)
          }
         
        })  
      }
    },
   

    //商品规格dialog
    handleSpecs(){
      this.dataForm.categoryId  = this.dataForm.categoryIds[this.dataForm.categoryIds.length - 1]
    
      console.log('categoryId======>>>>>' +  this.dataForm.categoryId)
      this.dialogFormSpecs = true 
    },

    // 往规格列表添加一条空规格信息
    addSku () {
      let sku = {
        name: '',
        image: '',
        price: null,
        stock: null
      }
      this.skuList.push(sku)
    },
    // 删除最后一条规格信息
    delSku () {
      const last = this.skuList.length - 1
      this.skuList.splice(last, 1)
    },

    //dialog关闭取消
    cancel(){
      this.dialogFormVisible = false
      this.categoryIds = []
      this.dialogFormSpecs = false 
      //规格清空
      this.skuList = []
      //
    },

    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          createGoods(this.dataForm).then(response => {
            this.list.unshift(response.data.data);
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row);
      this.categoryIds = row.categoryIds
      console.info(this.categoryIds)
      // if (this.dataForm.gallery.length > 0) {
      //   for (var i = 0; i < row.gallery.length; i++) {
      //     this.galleryFileList.push({
      //       name: row.gallery[i].substring(row.gallery[i].lastIndexOf("/") + 1),
      //       url: row.gallery[i]
      //     });
      //   }
      //}

      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          updateGoods(this.dataForm).then(() => {
            for (const v of this.list) {
              if (v.id === this.dataForm.id) {
                const index = this.list.indexOf(v);
                this.list.splice(index, 1, this.dataForm);
                break;
              }
            }
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleDelete(row) {
      deleteGoods(row).then(response => {
        this.$notify({
          title: "成功",
          message: "删除成功",
          type: "success",
          duration: 2000
        });
        const index = this.list.indexOf(row);
        this.list.splice(index, 1);
      });
    },

    //限制图片文件大小
    beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
    },
    handleDownload() {
      this.downloadLoading = true;
      import("@/vendor/Export2Excel").then(excel => {
        const tHeader = [
          "商品ID",
          "商品编号",
          "名称",
          "专柜价格",
          "当前价格",
          "是否新品",
          "是否热品",
          "是否在售",
          "首页主图",
          "宣传画廊",
          "商品介绍",
          "详细介绍",
          "商品主图",
          "商品单位",
          "关键字",
          "类目ID",
          "品牌商ID"
        ];
        const filterVal = [
          "id",
          "goodsSn",
          "name",
          "counterPrice",
          "retailPrice",
          "isNew",
          "isHot",
          "isOnSale",
          "listPicUrl",
          "gallery",
          "goodsBrief",
          "goodsDesc",
          "primaryPicUrl",
          "goodsUnit",
          "keywords",
          "categoryId",
          "brandId"
        ];
        excel.export_json_to_excel2(tHeader, this.list, filterVal, "商品信息");
        this.downloadLoading = false;
      });
    }
  }
};
</script>